//
//  YHPickImgView.swift
//  XLWB
//
//  Created by key on 16/6/30.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

private let itemId = "supItem"

private let itemSpac: CGFloat = 5 // item 之间的间距

//计算每个item的大小
private let itemWH = (screenW - spac * 2 - itemSpac * 2) / 3

class YHPickImgView: UICollectionView {

    
    //MARK: - 数据加载
    var pictureInfo: [YHPictureInfo]? {
        
        didSet{
            
            //有数据时 则有配图cellectionView 此时设置约束
            self.snp_updateConstraints { (make) -> Void in
                
                //计算collectionView大小 根据图片的数量计算
                let size = getCollectionViewSize(pictureInfo!.count)
                make.size.equalTo(size)
                
            }
            
            reloadData()
            
        }
        
    }
    
    //计算 collectionView大小
    func getCollectionViewSize(pictureNum: Int) -> CGSize {
        
        //计算整体collectionView的大小
        //有多少列
        let col = pictureNum == 4 ? 2 : (pictureNum >= 3 ? 3 : pictureNum)
        //有多少行
        let row = pictureNum == 4 ? 2 : ((pictureNum - 1) / 3 + 1)
        
        let collectionViewSizeW = itemWH * CGFloat(col) + itemSpac * CGFloat(col - 1)
        
        let collectionViewSizeH = itemWH * CGFloat(row) + itemSpac * CGFloat(row - 1)
        
        return CGSize(width: collectionViewSizeW, height: collectionViewSizeH)
        
    }
    
    
    //MARK: - 入口
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        //设置视图
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    //MARK: - 设置视图
    func setupUI() {
        
        backgroundColor = UIColor.clearColor()
        
        //设置代理
        self.dataSource = self
        self.delegate = self
        
        //注册cell
        self.registerClass(YHPickImgViewCell.self, forCellWithReuseIdentifier: itemId)
        
        //设置布局
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        
        flowLayout.itemSize = CGSize(width: itemWH, height: itemWH)
        
        flowLayout.minimumInteritemSpacing = 5
        
        flowLayout.minimumLineSpacing = 5
    }
    
}

//MARK: - 设置数据源方法
extension YHPickImgView:UICollectionViewDataSource, UICollectionViewDelegate, SDPhotoBrowserDelegate {
    
    //行
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return self.pictureInfo?.count ?? 0
        
    }
    
    //cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(itemId, forIndexPath: indexPath) as! YHPickImgViewCell
        
        cell.pictureInfo = self.pictureInfo![indexPath.item]
        
        return cell
        
    }
    
    
    //点击cell
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self;
        photoBrowser.currentImageIndex = indexPath.item;
        photoBrowser.imageCount = self.pictureInfo!.count
        photoBrowser.sourceImagesContainerView = self
        
        photoBrowser.show()
    }
    
    
    
    //MARK: - SDPhotoBrowserDelegate 代理方法
    
    // 返回临时占位图片（即原来的小图）
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        
        let cell = collectionView(self, cellForItemAtIndexPath: NSIndexPath(forItem: index, inSection: 0)) as! YHPickImgViewCell
        
        return cell.picImg.image
        
    }

    
    // 返回高质量图片的url
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        
        let url = (self.pictureInfo![index].thumbnail_pic ?? "" as NSString).stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        
        return NSURL(string: url)
        
    }
    
}



//MARK: - 自定义cell
class YHPickImgViewCell: UICollectionViewCell {
    
    //MARK: - 数据传递
    var pictureInfo: YHPictureInfo? {
        
        didSet{
            
            picImg.sd_setImageWithURL(NSURL(string: pictureInfo?.thumbnail_pic ?? ""), placeholderImage: UIImage(named: "timeline_card_top_background"))
            
        }
        
    }
    
    //MARK: 懒加载控件
    lazy var picImg: UIImageView = {
        
        let pic = UIImageView(image: UIImage(named: "timeline_card_top_background"))
        
        pic.contentMode = .ScaleAspectFill
        
        pic.clipsToBounds = true
        
        return pic
        
    }()
    
    
    //MARK: - 入口
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //添加子控件
        addChiledrenView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 添加子控件
    func addChiledrenView() {
        
        contentView.addSubview(picImg)
        
        
        
        //设置约束
        setSubViewFrame()
        
    }
    //设置约束
    func setSubViewFrame() {
        
        picImg.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
            
        }
        
        
    }
    
    
    
}

